<template>
    <div class="statistics">
        <el-divider content-position="left">性别统计</el-divider>
        <div id="statisticsGender" style="width:100%;">
            <el-table   :data="statisticsGender"   style="width: 100%">
                <el-table-column label="店铺"  prop="name"></el-table-column>
                <el-table-column label="总客流" prop="total"></el-table-column>
                <el-table-column label="男" prop="man"></el-table-column>
                <el-table-column label="男占比">
                    <template slot-scope="scope">
                        {{(scope.row.man / scope.row.total * 100).toFixed(2) + '%' }}
                    </template>
                </el-table-column>
                <el-table-column label="女" prop="women"></el-table-column>
                <el-table-column label="女占比">
                    <template slot-scope="scope">
                        {{(scope.row.women / scope.row.total * 100).toFixed(2) + '%' }}
                    </template>
                </el-table-column>
            </el-table> 
        </div>
        <br/>
        <el-divider content-position="left">按时间统计</el-divider>
        <div id="statistics" style="width:100%;">
        <span>选择查询的店铺:</span>
        <el-select v-model="searchParam.locationId" placeholder="请选择" @change="selectChange()">
            <el-option
            v-for="item in locationList"
            :key="item.id"
            :label="item.name"
            :value="item.id">
            </el-option>
        </el-select>
        <span>选择查询的类型:</span>
        <el-radio-group v-model="statisticsUrl" @change="radioGroupChange()">
            <el-radio-button label="statisticsDay">按日统计</el-radio-button>
            <el-radio-button label="statisticsWeek">按周统计</el-radio-button>
            <el-radio-button label="statisticsMonth">按月统计</el-radio-button>
        </el-radio-group>
            <!-- <el-table   :data="statistics.statistics"   style="width: 100%">
                <el-table-column label="店铺"  prop="name"></el-table-column>
                <el-table-column label="时间" prop="date"></el-table-column>
                <el-table-column label="新客" prop="newCustomers"></el-table-column>
                <el-table-column label="会员" prop="member"></el-table-column>
                <el-table-column label="总数" prop="total"></el-table-column>
            </el-table>  -->
            <div id="dateStatistics" style="width:100%; height:40vh"></div>
        </div>
        <div class="custom-age">
              <div class="title"></div>
              <div id="age-echarts"></div>
        </div>
        <el-divider content-position="left">回头客统计</el-divider>
        <div id="customers" style="width:100%;">
            <el-table   :data="customers"   style="width: 100%">
                <el-table-column label="店铺"  prop="name"></el-table-column>
                <el-table-column label="总客流" prop="total"></el-table-column>
                <el-table-column label="回头客" prop="customers"></el-table-column>
                <el-table-column label="回头客占比">
                    <template slot-scope="scope">
                        {{(scope.row.customers / scope.row.total * 100).toFixed(2) + '%' }}
                    </template>
                </el-table-column>
                
            </el-table> 
        </div>
        <el-divider content-position="left">会员统计</el-divider>
        <div id="customers" style="width:100%;">
            <el-table   :data="customers"   style="width: 100%">
                <el-table-column label="店铺"  prop="name"></el-table-column>
                <el-table-column label="总客流" prop="total"></el-table-column>
                <el-table-column label="会员数" prop="member"></el-table-column>
                <el-table-column label="会员占比">
                    <template slot-scope="scope">
                        {{(scope.row.member / scope.row.total * 100).toFixed(2) + '%' }}
                    </template>
                </el-table-column>
                
            </el-table> 
        </div>
    </div>
</template>

<script>
import request from '@/utils/request';
var echarts = require("echarts");
//引入 ECharts 主模块
var echarts = require("echarts/lib/echarts");
// 引入柱状图
require("echarts/lib/chart/bar");
// 引入提示框和标题组件
require("echarts/lib/component/tooltip");
require("echarts/lib/component/title");
export default {
    name: "statistics",
    data() {
        return {
            locationList: [],
            statistics: {},
            searchParam: {locationId: ''},
            statisticsUrl: 'statisticsDay',
            statisticsGender:[],
            customers:[]
        };
    },
    created() {
    },
    mounted(){
        this.getLocationList()
        this.getStatisticsGender()
        this.getAgeStatistics()
        this.getcustomers()
    },
    computed: {
    },
    methods: {
        getLocationList(){
            request({
                url: '/rest/customers/queryLocationList',
                method: 'post',
                data: {}
            }).then(res => {
                if(res.status){
                    this.locationList = res.data
                    if(this.locationList){
                        this.searchParam.locationId = this.locationList[0].id
                        this.getStatistics()
                    }
                }else{
                    this.$message.error(res.message);
                }
            }).catch((e) => {
                console.error(e)
                this.$message.error("网络错误!");
            });
        },
        getStatistics(){
            request({
                url: '/rest/customers/' + this.statisticsUrl,
                method: 'post',
                data: this.searchParam
            }).then(res => {
                if(res.status){
                    this.statistics = res.data
                    this.showDateStatistics()
                }else{
                    this.$message.error(res.message);
                }
            }).catch((e) => {
                console.error(e)
                this.$message.error("网络错误!");
            });
        },
        radioGroupChange(){
            this.getStatistics()
        },
        selectChange(){
            this.getStatistics()
        },
        getStatisticsGender(){
            request({
                url: '/rest/customers/statisticsGender',
                method: 'post',
                data: {}
            }).then(res => {
                if(res.status){
                    this.statisticsGender = res.data
                }else{
                    this.$message.error(res.message);
                }
            }).catch((e) => {
                console.error(e)
                this.$message.error("网络错误!");
            });
        },
        getcustomers(){
            request({
                url:'/rest/customers/statisticsCustomers',
                method:'post',
                data:{}
            }).then(res=>{
                if(res.status){
                    
                    this.customers= res.data
                }else{
                    this.$message.error(res.message);
                }
            }).catch((e) => {
                console.error(e)
                this.$message.error("网络错误!");
            });
        },
        showDateStatistics(){
            let statisticsData = {dates: [], series: [], names: ['总数','新客','会员','回头客']}
            let total = {
                name: '总数',
                type: 'line',
                data: []
            }
            let news = {
                name: '新客',
                type: 'line',
                data: []
            }
            let members = {
                name: '会员',
                type: 'line',
                data: []
            }
            let olds = {
                name: '回头客',
                type: 'line',
                data: []
            }
            this.statistics.statistics.forEach(element => {
                let date = element["date"]

                if(this.statisticsUrl == "statisticsWeek"){
                    date = date == 0 ? "周日" : "周" + date
                }

                statisticsData.dates.push(date);
                total.data.push(element['total'])
                news.data.push(element['newCustomers'])
                members.data.push(element['member'])
                olds.data.push(element['total'] - element['newCustomers'] - element['member'])
            });
            statisticsData.series.push(total, news, members, olds)
            // 基于准备好的dom，初始化echarts实例
            let warningChart = this.$echarts.init(document.getElementById("dateStatistics"));
            // 指定图表的配置项和数据
            let option = {
                title: {
                    text: '数据统计',
                    left: 'center',
                    textStyle:{color:'#000'}
                },
                tooltip: {
                    trigger: 'axis',
                    axisPointer: {
                        type: 'cross',
                        crossStyle: {
                            color: '#000'
                        }
                    }
                },
                toolbox: {
                    feature: {
                        dataView: {show: true, readOnly: false},
                        magicType: {show: true, type: ['line', 'bar']},
                        restore: {show: true},
                        saveAsImage: {show: true}
                    }
                },
                legend: {
                    orient: 'vertical',
                    left: 'left',
                    data: statisticsData.names,
                    textStyle:{color:'#000'}
                },
                xAxis: [
                    {
                        type: 'category',
                        data: statisticsData.dates,
                        name: '日期',
                        //textStyle:{color:'#fff'},
                        axisPointer: {
                            type: 'shadow'
                        }
                    }
                ],
                yAxis: [
                    {
                        type: 'value',
                        name: '个数',
                        // //nameTextStyle:{rich:{'a':{color:'#fff'}}},
                        min: 0,
                        axisLabel: {
                            formatter: '{value}'
                        }
                    }
                ],
                // dataZoom: [
                //     {
                //         show: false,
                //         // 开始位置的数值
                //         start: 0,
                //         // 结束位置的数值
                //         end: 50
                //     }
                // ],
                series: statisticsData.series
            };
            // 使用刚指定的配置项和数据显示图表。
            warningChart.setOption(option);
        },
         getAgeStatistics(){
        request({
        url: "/rest/customers/statisticsAge",
        method: "post",
        data: {locationId: this.locationList[this.checkedIndex]},
      })
        .then((res) => {
          if (res.status) {
            this.showAgeChart(res.data[0])
          } else {
            this.$message.error(res.message);
          }
        })
        .catch((e) => {
          console.error(e);
          this.$message.error("网络错误!");
        });
        },
        showAgeChart(ageData){
        
        let ageNames = ['0-9','10-20','21-35','36-50','51-70','71-100']
        let ageNums = []
        for(let k in ageNames){
            ageNums.push(ageData[ageNames[k]] || 0)
        }
        let ageChart = echarts.init(document.getElementById("age-echarts"));
        // 1.年龄柱状图
        ageChart.setOption({
            color: ["#3398DB"],
            tooltip: {
                trigger: "axis",
                axisPointer: {
                // 坐标轴指示器，坐标轴触发有效
                type: "shadow", // 默认为直线，可选为：'line' | 'shadow'
                },
            },
            title: {
                    text: '年龄段分析',
                    left: 'center',
                    textStyle:{color:'#000'}
                },
            grid: {
                left: "3%",
                right: "4%",
                containLabel: true,
            },
            xAxis: [
                {
                type: "category",
                data: ageNames,
                axisTick: {
                    alignWithLabel: true,
                    inside: true,
                    lengt: 0,
                    lineStyle: {
                    color: "#597487", //---默认取轴线的颜色
                    width: 1,
                    type: "solid",
                    },
                },
                axisLabel: {
                    show: true,
                    margin: 20,
                    textStyle: {
                    color: "#597487",
                    },
                },
                axisLine: {
                    show: true, //---是否显示

                    //------------------- 箭头 -------------------------
                    symbol: ["none", "arrow"], //---是否显示轴线箭头
                    symbolSize: [8, 8], //---箭头大小
                    symbolOffset: [0, 7], //---箭头位置

                    //------------------- 线 -------------------------
                    lineStyle: {
                    color: "#597487",
                    width: 1,
                    type: "solid",
                    },
                },
                },
            ],
            yAxis: [
                {
                type: "value",
                },
            ],
            series: [
                {
                name: "直接访问",
                type: "bar",
                barWidth: "60%",
                data: ageNums,
                label: {
                    //---图形上的文本标签
                    show: true,
                    position: "insideTop", //---相对位置
                    rotate: 0, //---旋转角度
                    color: "#96d2f4",
                },
                },
            ],
        });

        setTimeout(function () {
            ageChart.resize();
        }, 200);
        },

    }
};
</script>

<style lang="scss" scoped>
    .statistics {
        
        height: 100%;
        width: -webkit-fill-available;
    }
    .custom-age {
        width: 100%;
        height: 400px;
        margin-top: 20px;
        #age-echarts {
          width: 90%;
          height: 380px;
        }
      }
    //   #customers{
    //       margin-bottom: 20px;
    //   }
</style>
